<?php

namespace App\Lib\Users\Services;

use App\Constants\Users;
use App\Lib\_Error\ExecuteException;
use App\Lib\LibBaseService;
use App\Model\UsersModel;

class RobotService extends LibBaseService
{
    const DEFAULT_COIN = 3000;
    const DEFAULT_SCORE = 80000;

    /**
     * 创建机器人
     * @return UsersModel
     * @throws ExecuteException
     */
    public function create()
    {
        $robot = new UsersModel([
            'nickname' => RandomService::generateNickname(),
            'realname' => RandomService::generateUsername(),
            'id_sn' => RandomService::generateIdentity(),
            'mobile' => RandomService::generateMobile(),
            'coin' => self::DEFAULT_COIN,
            'score' => self::DEFAULT_SCORE,
            'type' => Users::TYPE_ROBOT,
        ]);
        if (!$robot->save()) {
            throw new ExecuteException('创建机器人失败');
        }
        return $robot;
    }

    /**
     * 获取一个空闲的机器人
     * @return UsersModel|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|null|object
     * @throws ExecuteException
     */
    public function getRobot()
    {
        $robot = UsersModel::query()->where('busy_status', '<>', Users::BUSY_STATUS_PLAYING)->first();
        if (!$robot) {
            return $this->create();
        }
        return $robot;
    }
}